$(function() {

	"use strict";



	window.Input = function(selector) {
		var $ele;

		var me = this;
		var rule = {
			required: true
		};

		var $err_ele;


		function init() {
			find_ele();
			parse_rule();
			me.load_validator();
			listen();

			// 获取 input error元素
			get_error_ele();
			// 隐藏 input error 
			// hide_err_message();
		}


		function hide_err_message() {

			$err_ele.hide();
		}

		function listen() {

			$ele.on('blur', function() {
				var r = me.validator.is_valid(me.get_val());
				// console.log('blur:r:', r);
				if (!r) {
					// 显示标签 以 inline-block 显示
					$err_ele.css({
						'display': 'inline-block'
					});
				} else {
					$err_ele.hide();
				}

			})
		}


		function get_error_ele() {
			$err_ele = $(get_input_error_selector());
		}

		function get_input_error_selector() {
			return "#" + $ele.attr('name') + '-' + 'input-error';
		}
		// name-input-error

		this.get_val = function() {
			return $ele.val();
		}

		this.load_validator = function() {
			var value = this.get_val();
			// 绑定到this 上面
			this.validator = new Validator(value, rule);
		}


		function parse_rule() {
			// "max:10|min:2|maxlength:20:minlength:2|required:true|numeric:false"
			var rule_str = $ele.data('rule');

			if (!rule_str) {
				return
			}
			let key;
			let val;

			var rule_arr = rule_str.split('|')
			for (var i = 0; i < rule_arr.length; i++) {
				[key, val] = rule_arr[i].split(':');
				rule[key] = JSON.parse(val);
			}

			// console.log(rule);
		}

		function find_ele() {
			if (selector instanceof jQuery) {
				$ele = selector;
			} else {
				$ele = $(selector);
			}

		}

		// call init  method 
		init();
	}





});
